<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use app\common\controller\Api;
use app\common\model\OrderPay;
use app\admin\model\Play as PlayModel;
use app\common\model\Order;
use app\common\model\OrderLog;

class Notify extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    protected $layout = '';
    
    public function index()
    {
        return $this->view->fetch();
    }


    public function returnurl()
    {
        $param = $this->request->param();
        \think\Log::write('returnurl'.json_encode($param));
    }


    public function notifyurl()
    {
        $param = $this->request->param();
        \think\Log::write('notifyurl'.json_encode($param));
        require_once(VENDOR_PATH . 'Yop-Sdk/autoload.php');
        $sdkConfigFile = VENDOR_PATH."Yop-Sdk/yop_sdk_config_default.json";
        $config = file_get_contents($sdkConfigFile);
        $config = json_decode($config,1);
        $source = $param['response'];
        $YopService = new \services\YopService();
        $json = $YopService->decrypt($source, $config['isv_private_key'][0]['value'], $config['yop_public_key'][0]['value']);
        $param = json_decode($json,1);
        if ($param['status']!='SUCCESS') {
            \think\Log::write('orderpay:回调状态不成功');
            echo '回调状态不成功';
            return;
        }

        //你可以在这里你的业务处理逻辑,比如处理你的订单状态、给会员加余额等等功能
        $OrderPay = OrderPay::where('pay_no',$param['orderId'])->find();
        if ($OrderPay['pay_status']==1) {
            \think\Log::write('orderpay:已支付');
            echo '已支付';
            return;
        }
        if (!$OrderPay || !$OrderPay['play_nos']) {
            \think\Log::write('paydata:无支付单号');
            echo '参数有误';
            return;
        }
        $User = new \app\common\model\User();
        $userinfo = $User->get($OrderPay['user_id']);
        $order_nos = [];
        $play_nos = [];
        Db::startTrans();
        try {
            // foreach ($play as $k1 => $v1) {
            $order = Db::name('order_pay_item')->alias('opi')->join('play_order po','po.play_order_no=opi.play_order_no')->field('po.*')->where(['opi.pay_no'=>$OrderPay['pay_no']])->select();
            // 每个店铺的支付总金额
            $sum = [];
            if ($order) {
                foreach ($order as $key => $value) {
                    $is_finish=0;
                    if (!in_array($value['play_no'], $play_nos)) {
                        $play_nos[] = $value['play_no'];
                    }
                    // 如果是大额返利，此时执行完成订单
                    $play = PlayModel::where('play_no', $value['play_no'])->find();
                    if ($value['order_status']==6 || ($value['order_status']==-9 && $value['is_fushen']==1)) {
                        // 分销和抽奖机会和积分
                        // OrderLog::create([
                        //     'play_order_id' => $value['id'],
                        //     'play_order_no' => $value['play_order_no'],
                        //     'info' => '订单完成',
                        //     'create_by' => $user['nickname'],
                        //     'create_by_id' => $user['id'],
                        //     'is_front' => 1,
                        // ]);
                        Order::where(['id'=>$value['id']])->update(['order_status'=>3,'is_pay'=>1,'pay_time'=>time()]);
                        $is_finish=2;
                    } else {
                        Order::where(['id'=>$value['id']])->update(['is_pay'=>1,'pay_time'=>time()]);
                        $is_finish=0;
                    }
                    
                    // orderlog
                    OrderLog::create([
                        'play_order_id' => $value['id'],
                        'play_order_no' => $value['play_order_no'],
                        'create_by' => $userinfo['nickname'],
                        'create_by_id' => $userinfo['id'],
                        'is_front' => 1,
                        'info' => '商家支付h5账单',
                        'is_finish' =>$is_finish,
                    ]);
                    $order_nos[] = $value['play_order_no'];
                    // 中间人佣金
                    $shop = Db::name('shop')->where(['shop_no'=>$value['shop_no']])->field('middleman_id,shop_no')->find();
                    $middleman = Db::name('middleman')->where(['id'=>$shop['middleman_id']])->field('rebate_amt,user_id')->find();
                    if (isset($middleman['rebate_amt']) && $middleman['rebate_amt']) {
                        $User->money($middleman['rebate_amt'], $middleman['user_id'], '经纪人收益', $value['play_order_no']);
                    }
                    $amt = round($value['service_charge_amt']+$value['actual_rebate_amt'],2);
                    if (!isset($sum[$shop['shop_no']])) {
                        $sum[$shop['shop_no']] = $amt;
                    } else {
                        $sum[$shop['shop_no']] = $sum[$shop['shop_no']]+$amt;
                    }
                }
            }
            $OrderPay->pay_status = 1;
            $OrderPay->tran_no = $param['uniqueOrderNo'];
            $OrderPay->save();

            // 更新商家账单
            $bill_list = Db::name('bill_list')->order('id DESC')->find();
            if ($sum) {
                foreach ($sum as $key => $value) {
                    $where = 'create_dt="'.$bill_list['create_dt'].'" and shop_no='.$key;
                    $bill_list = Db::name('bill_list')->where($where)->field('*')->find();
                    if ($bill_list) {
                        \think\Log::write('orderpay:'.$where);
                        $update = [];
                        $play_status = '正常';
                        $last_pay_time = time();// 到账时间
                        $play = Db::name('play')->where('play_status in (3,5) and shop_no='.$key.' and pay_status!=2')->where('update_dt<"'.date('Y-m-d H:i:s',time()-259200).'"')->count();
                        if ($play) {
                            $play_status = '紧急账单';
                        }
                        $play = Db::name('play')->where('play_status in (3,5) and shop_no='.$key.' and pay_status!=2')->where('update_dt<"'.date('Y-m-d H:i:s',time()-777600).'"')->count();
                        if ($play) {
                            $play_status = '异常账单';
                        }
                        $amount = $bill_list['total_money']-$value;
                        $update['last_pay_time'] = 0;
                        $update['total_money'] = 0;
                        $update['pay_status'] = '';
                        $update['nopay_dt'] = '1970-01-01 00:00:00';
                        if ($amount>0) {
                            $update['pay_status'] = '待支付';
                            $update['total_money'] = round($amount,2);
                            $corder = Db::name('play_order')->field('create_dt')->where(['shop_no'=>$key])->where('is_pay=0 and order_status in (3,6,-9) and create_dt<"'.substr($bill_list['create_dt'], 0,10).'"')->order('create_dt asc')->find();
                            if ($corder) {
                                $update['nopay_dt'] = $corder['create_dt'];
                            }
                        } else {
                            $update['pay_status'] = '已支付';
                            $update['last_pay_time'] = $last_pay_time;
                        }
                        $update['play_status'] = $play_status;
                        $update['update_dt'] = date('Y-m-d H:i:s',time());
                        Db::name('bill_list')->where('id='.$bill_list['id'])->update($update);
                    }
                }
            }
            Db::commit();
            foreach ($order as $o) {
                if ($o['order_status']==6) {
                    \fast\Http::get(config('chbc_domain').'/index/yunzhan/notify?order_sn='.$o['play_order_no'].'&state=3&source=2&origin=bdb');
                }
            }
        } catch (Exception $e) {
            Db::rollback();
            \think\Log::write('paydata:'.print_r($e->getMessage()));
            echo '处理有误';
            return;
        }
        //下面这句必须要执行,且在此之前不能有任何输出
        echo 'SUCCESS';exit;
    }

    // 订单直接分账回调，不用了
    public function dividenotifyurl()
    {
        $param = $this->request->param();
        \think\Log::write('dividenotifyurl'.json_encode($param));
        require_once(VENDOR_PATH . 'Yop-Sdk/autoload.php');
        $sdkConfigFile = VENDOR_PATH."Yop-Sdk/yop_sdk_config_default.json";
        $config = file_get_contents($sdkConfigFile);
        $config = json_decode($config,1);
        $source = $param['response'];
        $YopService = new \services\YopService();
        $json = $YopService->decrypt($source, $config['isv_private_key'][0]['value'], $config['yop_public_key'][0]['value']);
        $param = json_decode($json,1);
        if ($param['divideStatus']!='SUCCESS') {
            echo '分账回调状态不成功';
            return;
        }
        $divideDetail = json_decode($param['divideDetail'],1);
        Db::startTrans();
        try {
            $all = [];
            foreach ($divideDetail as $key => $value) {
                if ($value['ledgerNo']==$YopService->MerchantNo) continue;
                $data = [];
                $user_id = Db::name('middleman')->where('ledger_no',$value['ledgerNo'])->value('user_id');
                (new \app\common\model\User())->money($value['amount'], $user_id, '经纪人收益', $param['orderId']);
                $data['tran_no'] = $param['uniqueOrderNo'];
                $data['user_id'] = $user_id;
                $data['pay_no'] = $param['orderId'];
                $data['amount'] = $value['amount'];
                $data['ledger_no'] = $value['ledgerNo'];
                $data['divide_detail_no'] = $value['divideDetailNo'];
                $all[] = $data;
            }
            $isInsert = Db::name('order_pay_divide')->insertAll($all);
            $OrderPay = OrderPay::where('pay_no',$param['orderId'])->find();
            $OrderPay->is_divide = 1;
            $OrderPay->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            \think\Log::write('divideerror:'.print_r($e->getMessage()));
            echo '处理有误';
            return;
        }
        if ($isInsert) {
            echo 'SUCCESS';exit;
        }
    }

    // 非订单分账回调
    public function batchnotifyurl()
    {
        $param = $this->request->param();
        \think\Log::write('batchnotifyurl'.json_encode($param));
        require_once(VENDOR_PATH . 'Yop-Sdk/autoload.php');
        $sdkConfigFile = VENDOR_PATH."Yop-Sdk/yop_sdk_config_default.json";
        $config = file_get_contents($sdkConfigFile);
        $config = json_decode($config,1);
        $source = $param['response'];
        $YopService = new \services\YopService();
        $json = $YopService->decrypt($source, $config['isv_private_key'][0]['value'], $config['yop_public_key'][0]['value']);
        $param = json_decode($json,1);
        $divideDetail = json_decode($param['divideDetail'],1);
        $isInsert = 0;
        Db::startTrans();
        try {
            if ($divideDetail[0]['status']=='SUCCESS') {

                $user_withdrawal_log = Db::name('user_withdrawal_log')->where(['withdrawal_no'=>$param['divideRequestId']])->find();
                if ($user_withdrawal_log) {
                    $money = -1*$user_withdrawal_log['wallet'];
                    // 审核通过
                    $result = Db::name('user_withdrawal_log')->where(['withdrawal_no'=>$param['divideRequestId']])->update([
                        'log_status' => 1,
                        'handel_admin_id' => $user_withdrawal_log['user_id'],
                        'handel_time' => time(),
                        'batch_id' => $param['divideRequestId'],
                        'update_dt' => date('Y-m-d H:i:s'),
                    ]);
                    $res = (new \app\common\model\User())->money($money, $user_withdrawal_log['user_id'], '提现', $user_withdrawal_log['id']);
                    if (!$res) {Db::rollback();$this->error('提现有误');}
                    $isInsert = 1;
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            \think\Log::write('divideerror:'.print_r($e->getMessage()));
            echo '处理有误';
            return;
        }
        if ($isInsert) {
            echo 'SUCCESS';exit;
        }
    }

}
